/**
 * 
 */
package com.thon.controller.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.SimpleTimeZone;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.thon.entity.system.Attachment;
import com.thon.service.system.AttachmentService;

/**
 * @author THON
 * @email thon.ju@meet-future.com
 * @date 2011-11-24 下午01:37:57
 * @description:
 */
@Controller
@RequestMapping("/gravatar")
public class AttachmentController{
	private static final Log log = LogFactory.getLog(AttachmentController.class);

	@Autowired
	private AttachmentService attachmentService;
	
	@RequestMapping({"/{targetId}/{dimension}"})
	public void doDownloadAction(@PathVariable Integer targetId, @PathVariable String dimension, HttpServletResponse response) throws IOException {
		
		if (StringUtils.isNotBlank(dimension) 
				&& (StringUtils.equalsIgnoreCase(dimension, "30x30") || StringUtils.equalsIgnoreCase(dimension, "50x50") ||StringUtils.equalsIgnoreCase(dimension, "100x100"))) {
			download(targetId, dimension, response);
		}
		
	}
	
	public void download(Integer targetId, String dimension,HttpServletResponse response){
		try {
			Attachment attachment = attachmentService.getAttachment(targetId);
			attachment.setDimension(dimension);
			// read attachment content from local file
			AttachmentUtil.read(attachment);
			// prepare download
			if(!attachment.getContentType().matches("image/.*")) {
				response.setContentType(attachment.getContentType());
				response.setContentLength(attachment.getFileSize().intValue());
				response.setHeader("Content-Disposition","attachment; filename=\"" + attachment.getFileName() +"\"");
			}
			
			//添加Last-Modified和Cache-Control响应头信息
			SimpleDateFormat formatDate = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
			formatDate.setTimeZone(new SimpleTimeZone(0, "GMT"));
			response.addHeader("Last-Modified",formatDate.format(attachment.getCreatedDate()));
			response.addHeader("Cache-Control", "max-age=31536000");//最长缓存一年
			response.addHeader("Img-Width", attachment.getWidth()+"");//
			response.addHeader("Img-Height", attachment.getHeight()+"");//
			
			response.getOutputStream().write(attachment.getBytes());
		} catch (Exception e) {
			log.error("attachment find failed >> attachmentId:" + targetId);
		}
	}
	
	
	
}
